//
//  MagicMoveTransition.m
//  CATransition
//
//  Created by xuxiwen on 16/6/11.
//  Copyright © 2016年 xuxiwen. All rights reserved.
//

#import "MagicMoveTransition.h"
#import "QYXDailyTableViewCell.h"
#import "QYXDailyViewController.h"
#import "QYXDailyDetailViewController.h"
#import "QYXDailyDetailCollectionViewCell.h"

@implementation MagicMoveTransition


#pragma mark - 返回动画时间

- (NSTimeInterval)transitionDuration:(id<UIViewControllerContextTransitioning>)transitionContext
{
    return 0.3f;
}

#pragma mark - 两个VC过渡动画


- (void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext
{

    
    // 起始VC
    QYXDailyViewController *fromVC = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
    // 目的VC
    QYXDailyDetailViewController *toVC = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
    // 转场视图容器
    UIView *containerView = [transitionContext containerView];
    
    
    NSIndexPath *indexPath = [[fromVC.mainTableView indexPathsForSelectedRows] firstObject];
    fromVC.indexPath = indexPath;
    
    QYXDailyTableViewCell *cell = (QYXDailyTableViewCell *)[fromVC.mainTableView cellForRowAtIndexPath:indexPath];
    


    // 对Cell上面的图片 做截图 来实现过渡动画视图
//    UIImageView *screenShot = cell.mainImageView;
    UIView *screenShot = [cell.mainImageView snapshotViewAfterScreenUpdates:NO];

    screenShot.backgroundColor = [UIColor clearColor];
        screenShot.frame = fromVC.finiRect = [containerView convertRect:cell.mainImageView.frame fromView:cell.mainImageView.superview];
    // fromVC.finiRect 返回时获取cell上的坐标
    fromVC.backView = screenShot;
    fromVC.finiRect = screenShot.frame;
    cell.mainImageView.hidden = YES;
    
    
    // 设置第二个控制器的位置和透明度

    
    toVC.view.frame = [transitionContext finalFrameForViewController:toVC];
    toVC.view.alpha = 0;
    
    
    // 把动画前后的两个ViewController加到容器控制器中
    [containerView addSubview:toVC.view];
    [containerView addSubview:screenShot];

    // 注意添加顺序
    
    // 现在开始做动画
    
    [UIView animateWithDuration:[self transitionDuration:transitionContext] animations:^{
        // 调用自动布局
        [containerView layoutIfNeeded];

        fromVC.view.alpha = 1.0;
        // 布局坐标
        screenShot.frame = CGRectMake((kScreenWidth -30) *0.5, 100, 30, 30);
//        screenShot.frame = CGRectMake(0, 64, kScreenWidth, (toVC.mainCollectionView.frame.size.height - 64 - 49) / 3 * 2);
    } completion:^(BOOL finished) {
        cell.mainImageView.hidden = NO;
        
        // 动画截图移除View
        [screenShot removeFromSuperview];
        toVC.view.alpha = 1;

        // 动画结束
        
        // 一定不要忘记告诉系统动画结束
        // 执行
        [transitionContext completeTransition:!transitionContext.transitionWasCancelled];
}];

    
}






@end
